package cn.iurac.testsystem.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iurac.testsystem.constant.ImgDefaultName;
import cn.iurac.testsystem.entity.User;
import cn.iurac.testsystem.enums.RoleEnum;
import cn.iurac.testsystem.exception.UploadException;
import cn.iurac.testsystem.param.ResponseParam;
import cn.iurac.testsystem.service.UserService;
import cn.iurac.testsystem.util.QiniuUtil;
import cn.iurac.testsystem.util.ResponseUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.rmi.ServerException;

@RestController
@Api("图片资源controller")
public class ImageController {

    @Resource
    private QiniuUtil qiniuUtil;
    @Resource
    private UserService userService;

    @PostMapping("/user/upload/{username}")
    public ResponseParam uploadUser(@PathVariable("username")String username, @RequestParam("imgFile") MultipartFile file) throws UploadException, IOException {
        User user = userService.getByUsername(username);
        if(ObjectUtil.isNull(user)){
            throw new ServerException("没找到相应用户!");
        }
        String imgName = "";
        if(ObjectUtil.isNotNull(file) && !file.isEmpty()){
            imgName = qiniuUtil.upload(file);
        }
        if(StrUtil.isBlank(imgName)){
            RoleEnum roleEnum = RoleEnum.getByCode(user.getRole());
            if(ObjectUtil.equal(roleEnum,RoleEnum.SUPERADMIN)){
                imgName = ImgDefaultName.SUPERADMIN_ICON;
            }else if(ObjectUtil.equal(roleEnum,RoleEnum.ADMIN)){
                imgName = ImgDefaultName.ADMIN_ICON;
            }else if(ObjectUtil.equal(roleEnum,RoleEnum.TEACHER)){
                imgName = ImgDefaultName.TEACHER_ICON;
            }else{
                imgName = ImgDefaultName.STUDENT_ICON;
            }
        }
        user.setImg(imgName);
        ResponseParam responseParam = new ResponseParam();
        boolean status = userService.updateById(user);
        if (!status) {
            responseParam = ResponseUtil.getErrorResponseParam("系统错误！");
        }
        return responseParam;
    }
}
